<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>课程管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <style>
        .table-container {
            margin-top: 20px;
        }
        .search-box {
            margin-bottom: 20px;
        }
        .modal-content {
            padding: 20px;
        }
    </style>
</head>
<body>
<div class="container">
    <h2 class="my-4">课程管理系统</h2>

    <div class="card search-box">
        <div class="card-body">
            <div class="row">
                <div class="col-md-8">
                    <input type="text" class="form-control" id="searchInput" placeholder="输入课程名称搜索...">
                </div>
                <div class="col-md-2">
                    <button class="btn btn-primary w-100" onclick="searchCourse()">搜索</button>
                </div>
                <div class="col-md-2">
                    <button class="btn btn-success w-100" onclick="showAddModal()">新增课程</button>
                </div>
            </div>
        </div>
    </div>

    <div class="card table-container">
        <div class="card-body">
            <table class="table table-striped table-hover">
                <thead class="table-dark">
                <tr>
                    <th>课程编号</th>
                    <th>课程名称</th>
                    <th>学分</th>
                    <th>授课教师</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="courseBody">
                <!-- 课程数据将通过AJAX动态加载 -->
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- 新增/编辑课程模态框 -->
<div class="modal fade" id="courseModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitle">新增课程</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="courseForm">
                    <input type="hidden" id="courseId">
                    <div class="mb-3">
                        <label for="courseName" class="form-label">课程名称</label>
                        <input type="text" class="form-control" id="courseName" required>
                    </div>
                    <div class="mb-3">
                        <label for="credit" class="form-label">学分</label>
                        <input type="number" class="form-control" id="credit" min="1" max="10" required>
                    </div>
                    <div class="mb-3">
                        <label for="teacherSelect" class="form-label">授课教师</label>
                        <select class="form-select" id="teacherSelect" required>
                            <option value="" selected disabled>请选择教师</option>
                            <!-- 教师选项将通过AJAX动态加载 -->
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveCourse()">保存</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // 全局变量
    let allTeachers = [];
    let courseModal = new bootstrap.Modal(document.getElementById('courseModal'));

    // 页面加载时初始化
    $(document).ready(function() {
        loadCourses();
        loadTeachers();
    });

    // 加载课程列表
    function loadCourses() {
        $.ajax({
            url: '/course/getAllCourses',
            type: 'GET',
            success: function(courses) {
                renderCourseTable(courses);
            },
            error: function(xhr, status, error) {
                console.error('加载课程失败:', error);
                alert('加载课程列表失败，请稍后重试');
            }
        });
    }

    // 渲染课程表格
    function renderCourseTable(courses) {
        const tbody = $('#courseBody');
        tbody.empty();

        if (courses.length === 0) {
            tbody.append('<tr><td colspan="5" class="text-center">暂无课程数据</td></tr>');
            return;
        }

        courses.forEach(course => {
            const teacher = allTeachers.find(t => t.teacherNo === course.teacherNo);
            const teacherName = teacher ? teacher.name : '未分配';

            const tr = $(`
                <tr>
                    <td>${course.courseNo}</td>
                    <td>${course.courseName}</td>
                    <td>${course.credit}</td>
                    <td>${teacherName}</td>
                    <td>
                        <button class="btn btn-sm btn-warning me-2" onclick="editCourse(${course.courseNo})">编辑</button>
                        <button class="btn btn-sm btn-danger" onclick="deleteCourse(${course.courseNo})">删除</button>
                    </td>
                </tr>
            `);
            tbody.append(tr);
        });
    }

    // 加载教师列表
    function loadTeachers() {
        $.ajax({
            url: '/teacher/getAllTeachers',
            type: 'GET',
            success: function(teachers) {
                allTeachers = teachers;
                renderTeacherSelect();
            },
            error: function(xhr, status, error) {
                console.error('加载教师失败:', error);
                alert('加载教师列表失败，将无法分配教师');
            }
        });
    }

    // 渲染教师下拉框
    function renderTeacherSelect() {
        const select = $('#teacherSelect');
        select.empty().append('<option value="" selected disabled>请选择教师</option>');

        allTeachers.forEach(teacher => {
            select.append($(`<option value="${teacher.teacherNo}">${teacher.name} (${teacher.department})</option>`));
        });
    }

    // 搜索课程
    function searchCourse() {
        const keyword = $('#searchInput').val().trim();
        if (!keyword) {
            loadCourses();
            return;
        }

        $.ajax({
            url: '/course/search',
            type: 'GET',
            data: { courseName: keyword },
            success: function(courses) {
                renderCourseTable(courses);
            },
            error: function(xhr, status, error) {
                console.error('搜索课程失败:', error);
                alert('搜索课程失败，请稍后重试');
            }
        });
    }

    // 显示新增课程模态框
    function showAddModal() {
        $('#courseForm')[0].reset();
        $('#courseId').val('');
        $('#modalTitle').text('新增课程');
        courseModal.show();
    }

    // 显示编辑课程模态框
    function editCourse(courseNo) {
        $.ajax({
            url: `/course/selectCourse/${courseNo}`,
            type: 'GET',
            success: function(course) {
                if (!course) {
                    alert('未找到该课程');
                    return;
                }

                $('#courseId').val(course.courseNo);
                $('#courseName').val(course.courseName);
                $('#credit').val(course.credit);
                $('#teacherSelect').val(course.teacherNo || '');
                $('#modalTitle').text('编辑课程');
                courseModal.show();
            },
            error: function(xhr, status, error) {
                console.error('获取课程详情失败:', error);
                alert('获取课程详情失败，请稍后重试');
            }
        });
    }

    // 保存课程
    function saveCourse() {
        const courseId = $('#courseId').val();
        const courseName = $('#courseName').val().trim();
        const credit = $('#credit').val();
        const teacherNo = $('#teacherSelect').val();

        // 表单验证
        if (!courseName) {
            alert('请输入课程名称');
            return;
        }
        if (!credit || credit < 1 || credit > 10) {
            alert('请输入有效的学分(1-10)');
            return;
        }
        if (!teacherNo) {
            alert('请选择授课教师');
            return;
        }

        const courseData = {
            courseNo: courseId || null,
            courseName: courseName,
            credit: parseFloat(credit),
            teacherNo: parseInt(teacherNo)
        };

        const url = courseId ? '/course/updateCourse' : '/course/addCourse';
        const method = courseId ? 'PUT' : 'POST';

        $.ajax({
            url: url,
            type: method,
            contentType: 'application/json',
            data: JSON.stringify(courseData),
            success: function(response) {
                if (response === 'success') {
                    courseModal.hide();
                    loadCourses();
                    alert(courseId ? '课程修改成功' : '课程添加成功');
                } else {
                    alert('操作失败');
                }
            },
            error: function(xhr, status, error) {
                console.error('保存课程失败:', error);
                alert('保存课程失败，请稍后重试');
            }
        });
    }

    // 删除课程
    function deleteCourse(courseNo) {
        if (!confirm('确定要删除该课程吗？此操作不可撤销！')) {
            return;
        }

        $.ajax({
            url: `/course/delCouse/${courseNo}`,
            type: 'DELETE',
            success: function(response) {
                if (response === 'success') {
                    loadCourses();
                    alert('课程删除成功');
                } else {
                    alert('删除失败');
                }
            },
            error: function(xhr, status, error) {
                console.error('删除课程失败:', error);
                alert('删除课程失败，请稍后重试');
            }
        });
    }
</script>
</body>
</html>